<template lang="pug">
  .step-4
    Spin(v-if="spinShow" size="large" fix)
    Table.hasTitle-table.beautiful-table(:columns="contractsThead" :data="contractsTableData" :stripe="true")
      ._table_header(slot="header")
        ._button.pull-right.mr-20
          //- i-button(type="info" @click="showAddModal()") 新增
      template(slot-scope="{ row, index }" slot="attachmentName")
        //- .und-line.mr-10(v-for="(item,index) in row.attachments" @click="downFiel(item.id, item.name)") {{item.name}}
        Poptip(trigger="hover" title="合同附件")
          div(slot="content")
            .u-d-info(v-for="(item, index) in row.attachments" :key="index" @click="downFiel(item.id, item.name)") {{item.name}}
            span(v-if="row.attachments.length < 1") 未上传
          Button(size="small") 查看
      template(slot-scope="{ row, index }" slot="operation")
        Button.mr-10(type="text" @click="editContract(row)") 编辑
        Button(type="text" @click="deleteContract(row.id)") 删除
    Modal.has-bg.step-4-add(v-model="addContractModal" :title="modalTitle" @on-cancel="cancel")
      Form(:label-width="130")
        FormItem.mb-10(label="档案号：")
          Input(v-model="formValidate_t4.documentNo" placeholder="请输入")
        FormItem.mb-10(label="合同类型：")
          Select.input-has-border(v-model="formValidate_t4.contractType" placeholder="请选择合同类型" :label-in-value="true" filterable style="width:100%")
            Option(v-for="(item, index) in arrListDown.ContractType" :value="item.value" :key="index") {{ item.label }}
        FormItem.mb-10.ivu-form-item-required(label="合同编号：")
          Input(v-model="formValidate_t4.code" placeholder="请输入" disabled)
        FormItem.mb-10.ivu-form-item-required(label="合同年限：")
          Input(v-model="formValidate_t4.duration" placeholder="请输入")
        FormItem.mb-10.ivu-form-item-required(label="合同开始时间：" prop="startDate")
          DatePicker(:value="formValidate_t4.startDate" type="date" placeholder="请选择" @on-change="startDateChange")
        FormItem.mb-10.ivu-form-item-required(label="合同结束时间：" prop="endDate")
          DatePicker(:value="formValidate_t4.endDate" type="date" placeholder="请选择" @on-change="endDateChange")
        FormItem.mb-10.ivu-form-item-required(label="附件上传：")
          Upload(:before-upload="createHandleUpload" multiple ref="addUpload" :show-upload-list="true" action="")
            Button(type="info" icon="ios-cloud-upload-outline") 点击上传
          template(v-for="(item,index) in fileArr")
            .my-tag.mr-20
              .my-tag-inner {{item.name}}
              .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile(index)")
          template(v-for="(item,index) in formValidate_t4.attachments")
            .my-tag.mr-20
              .my-tag-inner(@click="downFiel(item.id, item.name)") {{item.name}}
              .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteContractsFile(item.id)")
        FormItem.mb-10(label="备注：")
          Input(v-model="formValidate_t4.remark" type="textarea" placeholder="请输入")
      template(slot="footer")
        Button(@click="cancel") 取消
        Button(type="info" @click="saveStep_4" :disabled="btnDisabled") 确定

</template>

<script>
import dataApi from '@/api/data.js'
import config from '@/config'
import { Common } from '@/utils/common.js'
import { setTimeout } from 'timers';
import { constants } from 'zlib';
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'stpe_4',
  props: {
    customerId: String
  },
  data () {
    return {
      btnDisabled: false,
      modalType: true, // 0-编辑，1-新增
      modalTitle: '',
      areaArr: [],
      mustHave: false, // 必填
      spinShow: false, // 加载中
      isCheck: true, // 是否处于查看状态
      addContractModal: false, // 添加合同弹窗
      fileArr: [],
      formValidate_t4: {
        documentNo: '',
        contractType: '', // 合同类型
        code: '', // 合同编号
        duration: '', // 合同年限
        startDate: '', // 合同开始时间
        endDate: '', // 合同结束时间
        file: '', // 合同附件
        remark: '', // 合同备注
        id: '', // 合同ID
        rowVersion: '' // 版本
      },
      contractsThead: [ // 合同信息表头
        {
          title: '合同类型',
          minWidth: 150,
          key: 'contractType'
        },
        {
          title: '档案号',
          minWidth: 150,
          key: 'documentNo'
        },
        {
          title: '合同编号',
          minWidth: 150,
          key: 'code'
        },
        {
          title: '合同年限',
          minWidth: 150,
          key: 'duration'
        },
        {
          title: '合同开始时间',
          minWidth: 150,
          key: 'startDate',
          render: (h, params) => {
            let row = params.row
            let times = ''
            if (row.startDate) {
              times = row.startDate.slice(0, 10)
              return h('span', times)
            } else {
              return h('span', times)
            }
          }
        },
        {
          title: '合同结束时间',
          minWidth: 150,
          key: 'endDate',
          render: (h, params) => {
            let row = params.row
            let times = ''
            if (row.startDate) {
              times = row.endDate.slice(0, 10)
              return h('span', times)
            } else {
              return h('span', times)
            }
          }
        },
        {
          title: '合同附件',
          minWidth: 150,
          slot: 'attachmentName',
          key: 'attachmentName'
        },
        {
          title: '备注',
          minWidth: 150,
          key: 'remark'
        },
        {
          title: '终止合作原因',
          minWidth: 150,
          key: 'terminationReason'
        },
        // {
        //   title: '操作',
        //   minWidth: 100,
        //   slot: 'operation',
        //   align: 'center'
        // }
      ],
      contractsTableData: [], // 合同表格数据
      uploadBaseUrl: baseUrl,
      arrListDown:{
        ContractType:[]
      }
    }
  },
  created () {
    this.getContracts()
    this.getEnum()
  },
  methods: {
    // 数据字典
    getEnum () {
      let typeName = 'ContractType'
      Common.getSelectValueList(typeName, this.arrListDown)
      setTimeout(()=>{
        console.log(this.arrListDown)
      },2000)
    },
    // 删除合同
    deleteContract (id) {
      dataApi.DeleteContract({
        id: id
      }).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.getContracts()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 删除合同附件
    deleteContractsFile (id) {
      // this.formValidate_t4.attachments = this.formValidate_t4.attachments.filter(item => {
      //   return item.id !== id
      // })
      dataApi.deleteAttachments({
        id: id
      }).then(res => {
        this.formValidate_t4.attachments = this.formValidate_t4.attachments.filter(item => {
          return item.id !== id
        })
      })
    },
    // 获取合同信息
    getContracts () {
      this.spinShow = true
      dataApi.getContracts({
        id: this.customerId
      }).then(res => {
        console.log(res)
        this.contractsTableData = res.data.data
        this.spinShow = false
      })
    },
    openModal (Boolean) {
      this.modalType = Boolean
      this.addContractModal = true
      if (this.modalType) {
        this.fileArr = []
        this.modalTitle = '添加合同'
        dataApi.getDefaultContractNo().then(res => {
          this.formValidate_t4.code = res.data.data
        })
      } else {
        this.modalTitle = '编辑合同'
      }
    },
    // 打开添加合同弹窗
    showAddModal () {
      this.formValidate_t4 = {
        documentNo: '',
        attachments: [],
        code: '', // 合同编号
        contractType:'',// 合同类型
        duration: '', // 合同年限
        startDate: '', // 合同开始时间
        endDate: '', // 合同结束时间
        file: '', // 合同附件
        remark: '', // 合同备注
        id: '', // 合同ID
        rowVersion: '', // 版本
      }
      this.openModal(true)
    },
    // 合同起止时间
    createDateChange (val) {
      console.log(val)
      this.formValidate_t4.startDate = val[0]
      this.formValidate_t4.endDate = val[1]
    },
    // 合同开始时间
    startDateChange (val) {
      this.formValidate_t4.startDate = val
    },
    endDateChange (val) {
      this.formValidate_t4.endDate = val
    },
    // 上传合同附件
    createHandleUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      console.log('file: ', file)
      console.log('fileExt: ', fileExt)
      if (fileExt === 'exe') {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '不能上传.exe文件'
        })
        return false
        this.fileArr.push(file)
        console.log(this.fileArr)
        return false
      } else {
        this.fileArr.push(file)
        console.log(this.fileArr)
        return false
      }
      
    },
    deleteFile (index) {
      this.fileArr.splice(index, 1)
    },
    // 编辑合同
    editContract (obj) {
      this.openModal(false)
      this.formValidate_t4 = obj
      this.addContractModal = true
      this.fileArr = []
    },
    downFiel (id, fileName) {
      console.log(id, fileName)
      const suffixs = ['JPG', 'JPEG', 'PNG']
      let suffix = fileName.substring(fileName.lastIndexOf('.') + 1).toUpperCase()
      console.log(suffix)
      if (suffixs.includes(suffix)) {
        this.$emit('preview', {
          url: this.uploadBaseUrl + '/Customer/DownLoadAttachment?id=' + id,
          id: id,
          fileName: fileName
        })
      } else if(suffix == 'PDF'){
        dataApi.getDownLoadAttachment({
          id: id
        }).then(res => {
          console.log(res)
          let blob = new Blob([res.data], { type: 'application/pdf;chartset=UTF-8' })
          if ('download' in document.createElement('a')) {
            let objectUrl = URL.createObjectURL(blob)
            console.log(objectUrl)
            // let objectUrl = URL.createObjectURL(new Blob([res.data],{type: 'application/octet-stream'}))
            // 文件地址
            window.open(objectUrl);
          } else {
            navigator.msSaveBlob(blob, fileName)
          }
        })
      } else {
        dataApi.getDownLoadAttachment({
          id: id
        }).then(res => {
          console.log(res)
          let blob = new Blob([res.data], { type: 'application/octet-stream' })
          if ('download' in document.createElement('a')) {
            let objectUrl = URL.createObjectURL(blob)
            console.log(objectUrl)
            // let objectUrl = URL.createObjectURL(new Blob([res.data],{type: 'application/octet-stream'}))
            // 文件地址
            const link = document.createElement('a')
            link.download = fileName
            link.href = objectUrl
            link.click()
          } else {
            navigator.msSaveBlob(blob, fileName)
          }
        })
      }
    },
    // 第四步，添加合同信息
    saveStep_4 () {
      if (this.fileArr.length + this.formValidate_t4.attachments.length > 0) {
        let formData = new FormData()
        formData.append('documentNo', this.formValidate_t4.documentNo)
        formData.append('code', this.formValidate_t4.code)
        formData.append('duration', this.formValidate_t4.duration)
        formData.append('startDate', this.formValidate_t4.startDate)
        formData.append('endDate', this.formValidate_t4.endDate)

        // formData.append('atta', this.formValidate_t4.file)
        formData.append('remark', this.formValidate_t4.remark)
        formData.append('customerId', this.customerId)
        formData.append('id', this.formValidate_t4.id)
        formData.append('contractType', this.formValidate_t4.contractType)
        formData.append('rowVersion', this.formValidate_t4.rowVersion)
        this.fileArr.forEach(item => {
          formData.append('atta', item)
        })

        this.btnDisabled = true
        dataApi.postContract(formData, this.customerId).then((res) => {
          if (res.data.code === 200) {
            this.$Message.success(res.data.message)
            this.addContractModal = false
            setTimeout(() => {
              this.btnDisabled = false
            }, 1000)
            this.getContracts()
          } else {
            
            this.$Message.error({
              content: res.data.message,
              duration: 10,
              closable: true
            })
            this.btnDisabled = false
          }
        })
      } else {
        this.$Message.warning('请选择合同附件')
      }
    },
    cancel () {
      this.addContractModal=false
      this.getContracts()
    }
  }
}
</script>
<style lang="less">
  .step-4-add{
    .ivu-input[disabled]{
      color: #333;
    }
  }
</style>

<style lang="less" scoped>
  .und-line{
    text-decoration: underline;
    cursor: pointer;
    &:hover{
      color: #2d8cf0;
    }
  }
</style>
